package com.xiaozhichao.databafflesys.admin.config;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author:xiaozhichao
 * @date:2021/3/26
 */
@Component
@Aspect
public class ControllerAspect implements Ordered {
    public Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(* com.xiaozhichao.databafflesys.admin.controller.*.*(..)) " +
            "&& (@annotation(org.springframework.web.bind.annotation.ResponseBody))")
    private void pointCutMethod() {

    }

    @Around("pointCutMethod()")
    public Object doAround(ProceedingJoinPoint jp) throws Throwable {
        Object[] args = jp.getArgs();
        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        String loggerPre = methodSignature.getDeclaringType().getSimpleName() + "." + methodSignature.getMethod().getName();
        StringBuffer loggerStr = new StringBuffer(loggerPre);
        loggerStr.append(" 请求 : ");
        for (Object obj : args) {
            if (obj != null && !BindingResult.class.isAssignableFrom(obj.getClass()) && !MultipartFile.class.isAssignableFrom(obj.getClass())) {
                loggerStr.append("[");
                loggerStr.append(JSONObject.toJSONString(obj));
                loggerStr.append("]");
            }
        }
        logger.info(loggerStr.toString());
        Object result = jp.proceed();
        logger.info(loggerPre + " 响应 : [" + JSONObject.toJSONString(result) + "]");
        return result;
    }

    @Override
    public int getOrder() {
        return 1;
    }

}
